package com.lntea.netty.demo.nio;

import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ByteBufferTest {
    
    @Test
    public void testByteBuffer() throws IOException, URISyntaxException {
        RandomAccessFile file = new RandomAccessFile(new File(this.getClass().getResource("input.txt").toURI()), "rw");
        FileChannel channel = file.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(10);
        int read = channel.read(buffer);
        
        StringBuffer sb = new StringBuffer();
        
        while(read!=-1){
            buffer.flip();
            
            while(buffer.hasRemaining()){
                System.out.println("isDirect:"+buffer.isDirect());
                System.out.println("capacity:"+buffer.capacity());
                System.out.println("limit:"+buffer.limit());
                System.out.println("position:"+buffer.position());
                System.out.println("remaining:"+buffer.remaining());
                char c = (char)buffer.get();
                System.out.println("output:"+c);
                sb.append(c);
            }
            
            buffer.compact();
            read = channel.read(buffer);
        }
        
        file.close();
        System.out.println(sb.toString());
    }
}
